** Preparing oil shock variables

use "$project_path/data/3_cleaned/outcomes", clear
egen country_id = group(Country)
xtset country_id Year
gen signed_lag_growth_crude = L.growth_crude_price if oil_net_importer==1
replace signed_lag_growth_crude = -L.growth_crude_price if oil_net_importer==0
gen signed_lag2_growth_crude = L2.growth_crude_price if oil_net_importer==1
replace signed_lag2_growth_crude = -L2.growth_crude_price if oil_net_importer==0
egen oil_shock = rowmean(signed_lag_growth_crude signed_lag2_growth_crude)
keep Country Year oil_shock
merge 1:m Country Year using "$project_path/data/4_regdata/regdata", keep(using match) nogen

_pctile oil_shock if abs(runvar)<=15, percentiles(50 66.6666 75) 
gen subsample_above_median = 1 if oil_shock>=r(r1) & oil_shock!=.
gen subsample_top_tercile = 1 if oil_shock>=r(r2) & oil_shock!=.
gen subsample_top_quartile = 1 if oil_shock>=r(r3) & oil_shock!=.

gen subsample_post737907 = 1 if (oil_net_importer==1 & inlist(Year, 1974, 1975, 1976, 1977, 1980, 1981, 1982, 1983)) | inlist(Year, 2008, 2009, 2010, 2011)

** Regressions

log using "$project_path/output/appendix_tables/Appendix_Table_E4.smcl", replace

// Column 1 (Baseline)
rdrobust diff_m1_chix_econ runvar, all
rdrobust std_diff_m1_hdi runvar, all
rdrobust std_diff_m1_democracy_index runvar, all
rdrobust diff_m1_general_chix runvar, all

// Column 2 (Above median oil shock)
rdrobust diff_m1_chix_econ runvar if subsample_above_median==1, all
rdrobust std_diff_m1_hdi runvar if subsample_above_median==1, all
rdrobust std_diff_m1_democracy_index runvar if subsample_above_median==1, all
rdrobust diff_m1_general_chix runvar if subsample_above_median==1, all

// Column 3 (Top tercile oil shock)
rdrobust diff_m1_chix_econ runvar if subsample_top_tercile==1, all
rdrobust std_diff_m1_hdi runvar if subsample_top_tercile==1, all
rdrobust std_diff_m1_democracy_index runvar if subsample_top_tercile==1, all
rdrobust diff_m1_general_chix runvar if subsample_top_tercile==1, all

// Column 4 (Top quartile oil shock)
rdrobust diff_m1_chix_econ runvar if subsample_top_quartile==1, all
rdrobust std_diff_m1_hdi runvar if subsample_top_quartile==1, all
rdrobust std_diff_m1_democracy_index runvar if subsample_top_quartile==1, all
rdrobust diff_m1_general_chix runvar if subsample_top_quartile==1, all

// Column 5 (Post global shocks)
rdrobust diff_m1_chix_econ runvar if subsample_post737907==1, all
rdrobust std_diff_m1_hdi runvar if subsample_post737907==1, all
rdrobust std_diff_m1_democracy_index runvar if subsample_post737907==1, all
rdrobust diff_m1_general_chix runvar if subsample_post737907==1, all

log close

*** Building .tex table
// Regressions 
#delimit ;
local outcomes  
		diff_m1_chix_econ
		std_diff_m1_hdi
		std_diff_m1_democracy_index
		diff_m1_general_chix
;
#delimit cr		

local subsample_count 5

// Initialize matrix of results and define value labels
local ncols = `subsample_count'*2
local nrows = 8
//Prepare matrix of coefficients and other statistics
mat Coefs = J(`nrows', `ncols', .)

mat list Coefs
	
local subsamples "_above_median _top_tercile _top_quartile _post737907"

//inizialize indices
local row = 1
local next_row = `row' + 1

foreach v in `outcomes'{
	//Initialize indices
	local col = 1
	local pval_col = `subsample_count' + 1

	rdrobust `v' runvar, all
	
	//Store estimates and stats
	local b_`col': di %5.3f e(tau_cl)
	local se_`col': di %5.3f e(se_tau_rb)
	local p_`col': di %5.3f e(pv_rb)

	mat Coefs[`row',`col'] = `b_`col''
	mat Coefs[`next_row',`col'] = `se_`col''
	mat Coefs[`row',`pval_col'] = `p_`col''	
	
	
	foreach sub in `subsamples'{
		
		local ++col	
		local ++pval_col
		rdrobust `v' runvar if subsample`sub' == 1, all
		
		//Store estimates and stats
		local b_`col': di %5.3f e(tau_cl)
		local se_`col': di %5.3f e(se_tau_rb)
		local p_`col': di %5.3f e(pv_rb)
	
		mat Coefs[`row',`col'] = `b_`col''
		mat Coefs[`next_row',`col'] = `se_`col''
		mat Coefs[`row',`pval_col'] = `p_`col''	
		
	}
	
	local row = `row' + 2
	local next_row = `row' + 1
}

mat list Coefs

********************************************************************************
* 								EXPORT TABLE
********************************************************************************			
	// Clear the dataset, and use the matrix as dataset			

	clear
	svmat Coefs

	//	input variable names
	gen varname = ""
	gen temp = _n
	replace varname = "\textbf{Economic performance}" if temp == 1
	replace varname = "SE_1" if temp == 2
	replace varname = "\textbf{HDI}" if temp == 3
	replace varname = "SE_2" if temp == 4
	replace varname = "\textbf{Democracy}" if temp == 5
	replace varname = "SE_3" if temp == 6
	replace varname = "\textbf{General index}" if temp == 7
	replace varname = "SE_4" if temp == 8
	
	order varname, first
	drop temp
	  
	//Adjust the table before exporting
	replace varname = "" if strpos(varname, "SE_")>0
	order varname
	
	// Rename cols and labels
	forvalues n = 1/`subsample_count'{
		rename Coefs`n' Model`n'
	}
	//Cols where we store pvalues
	local n_min = `subsample_count' + 1
	local n_max = `subsample_count'*2
	local i = 1
	forvalues n = `n_min'/`n_max'{
		rename Coefs`n' P_Model`i'
		local ++i
	}
	
	label var varname ""
	label var Model1 "Baseline"
	label var Model2 "Above median"
	label var Model3 "Top tercile"
	label var Model4 "Top quartile"
	label var Model5 "Post 73/79/07"
	
		
	// Convert to string and add options
	forvalues i = 1/`subsample_count'{
		tostring Model`i', replace force format(%04.3f)
		replace Model`i'= "" if Model`i'=="."
		//Add parenthesis to SE and P-val
		replace Model`i' = "(" + Model`i' + ")" if missing(varname) & Model`i' !=""	

	}
	
	// Add stars
	local 3_star 0.01
	local 2_star 0.05
	local 1_star 0.10
	
	forvalues i = 1/`subsample_count'{
		
		replace Model`i' = Model`i' + "***" if P_Model`i' < `3_star'
		replace Model`i' = Model`i' + "**" if P_Model`i' < `2_star' & P_Model`i' > `3_star'
		replace Model`i' = Model`i' + "*" if P_Model`i' < `1_star' & P_Model`i' > `2_star'
		
		drop P_Model`i'
	}
	
	foreach var of varlist _all {
	qui replace `var' = ustrtrim(`var')	
}
	
	local title = "Effects of electoral turnovers taking place in adverse economic conditions"
	local filename = "baseline_het_oil_shock"
	local output "$project_path/output/appendix_tables/Appendix_Table_E4.tex"
	local headerlines = " & &  \multicolumn{3}{c}{\textbf{Adverse oil price growth}} & \textbf{Global shocks}"
	local footnote = "\caption*{\footnotesize \emph{Notes}: This table reports estimated effects of electoral turnovers for the full sample in column (1), and for the subsamples of elections with adverse oil price growth above the 50th, 66.6th, and 75th percentiles (in columns 2 to 4). These percentiles are measured among elections with a running variable between -15pp and +15pp. The adverse oil price growth variable is the average yearly growth in oil prices in the two years before the election for net oil importers, and the opposite of this variable for net oil exporters (see Section \ref{sec:externalValidity} for details). In column (5), we restrict the sample to elections taking place in the four years following three global economic shocks: the 1973 and 1979 oil crises in oil-importing countries, and the 2007-08 financial crisis. Namely, we look at elections taking place between 1974-77 and 1980-83 in net oil-importing countries, as well as in 2008-11, worldwide. $^{*} p<0.10,^{**} p<0.05,^{***} p<0.01$.}"
	
	texsave using "`output'", replace title("`title'") varlabels noendash ///
							footnote("`footnote'") ///
							headerlines("`headerlines'" "& (1) & (2) & (3) & (4) & (5)" ) ///
							frag nofix marker("tab:`filename'") location(H)
